<?php

namespace App\Services\Tools;

//require_once VENDOR_PATH . 'aliyuncs/aliyun-oss-php-sdk/autoload.php';
//include_once VENDOR_PATH . 'aliyuncs/aliyun-php-sdk-core/Config.php';

use Illuminate\Support\Facades\Log;

class HelperService {
    public static  function uniqidReal($lenght = 13) {
        // uniqid gives 13 chars, but you could adjust it to your needs.
        if (function_exists("random_bytes")) {
            $bytes = random_bytes(ceil($lenght / 2));
        } elseif (function_exists("openssl_random_pseudo_bytes")) {
            $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
        } else {
            throw new Exception("no cryptographically secure random function available");
        }
        return substr(bin2hex($bytes), 0, $lenght);
    }


    public static function curl_gets($url, $get_data = []) {
        //构造请求参数
        $param = http_build_query($get_data);
        $url = $url . '?' . $param;
        //初始化
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($code != 200) return false;
        curl_close($ch);
        return json_decode($output, true);
    }

    public static function CurlPost($url, $post_data = []) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //请求头
//        curl_setopt($ch, CURLOPT_HEADER, $header);
        //设置请求方式为POST
        curl_setopt($ch, CURLOPT_POST, true);
        //post变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        //输出
        $output = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($code != 200) {
            return ['code' => $code, 'data' => false];
        }
        curl_close($ch);
        return json_decode($output, true);
    }

    // 同步发送行为上报请求
    public static function actionReport($data) {
        try {
            if (env('APP_ENV') == 'local') {
                $url = env('LOCAL_NAPI_HOST');
            } else {
                $url = env('PRODUCTION_NAPI_HOST');
            }
            $url = $url . '/' . "service/action-hook/report";

            $result = static::CurlPost($url, $data);

            return $result;
        } catch (\Exception $e) {
            //记录日志
            Log::error('访问钩子接口失败:' . $e->getMessage());
        }

        return true;
    }

//调用公会接口的密钥生成
    public static function SociatySecretKey($param) {
        ksort($param);
        $param_str = http_build_query($param) . 'GMAyz1AXBkNTgKjFuef3';
        return md5($param_str);
    }


    public static function todayLeftTime() {
        return (strtotime(date('Ymd')) + 86400 - time());
    }
    //盲盒价格
    public static function blindBoxPrice(){
        $price =[
            'gold'=>600,
            'silver'=>2100,
            'copper'=>600,
        ];
        return $price;
     }


    public static function giftRank($money = 0) {
        if ($money < 500) {
            return '白色';
        } elseif ($money >= 500 && $money < 5000) {
            return '绿色';
        } elseif ($money >= 5000 && $money <= 29998) {
            return '蓝色';
        } elseif ($money > 29998 && $money < 200000) {
            return '紫色';
        } else {
            return '橙色';
        }
    }

    public static function popularity($room_id) {
//        $map = [
//            'expiry_time' => ['gt', time()],
//            '`left`'      => ['gt', 0],
//            'room_id'     => $room_id
//        ];
//        $gift_popularity = M('Popularity')->where($map)->sum('`left`');
//        $online_popularity = M('RoomJoin')->where(['room_id' => $room_id])->sum('popularity');
//        return ($online_popularity + $gift_popularity);
    }

    public static function queue($queue, $class, $args = null, $trackStatus = false) {
        vendor('php-resque.autoload');
        \Resque::enqueue($queue, $class, $args, $trackStatus);
    }

    //获取系统房用户ID
    public static function getSysRoomUserid() {
//        $sys_room_list = S('sys_room_list');
//        if ($sys_room_list === false) {
//            $sys_room_list = D("Api/UserRoom")->where(['sys_type_id' => ['gt', 0]])->getField('id,user_id', true);
//            S('sys_room_list', $sys_room_list);
//        }
//        return $sys_room_list;
    }

    public static function arraySort($array, $keys, $sort = 'asc') {
        $newArr = $valArr = [];
        foreach ($array as $key => $value) {
            $valArr[$key] = $value[$keys];
        }
        ($sort == 'asc') ? asort($valArr) : arsort($valArr);
        reset($valArr);
        foreach ($valArr as $key => $value) {
            $newArr[$key] = $array[$key];
        }
        return $newArr;
    }

    //mode: 1get 2post
    public static function httpRequest($url, $data = [], $mode = 1, $header = []) {
        $headers = [
            "Content-Type: application/json; charset=utf-8",
            "Accept: application/json",
            "Cache-Control: no-cache",
            "Pragma: no-cache"
        ];
        if (!empty($header)) {
            $headers = array_merge($headers, $header);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 60); //设置超时

        if ($mode == 2) {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_FORCE_OBJECT));
        } else {
            if ($data) {
                $querystring = http_build_query($data);
                $url = $url . '?' . $querystring;
            }
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        if (substr($url, 0, 5) == 'https') {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    public static function wxNickNameFormat($nickName) {
        $value = json_encode($nickName);
        $value = preg_replace("/\\\u[ed][0-9a-f]{3}\\\u[ed][0-9a-f]{3}/", "*", $value);
        return json_decode($value);
    }

    public static function jwtEncode($data = []) {
//        if (APP_STATUS != 'production') {
            return self::generateToken(['user_id' => $data['userId']]);
//        }

        require_once PLUGINS . '/JWT.php';
        $jwt = new \JWT();
        $data['iat'] = time();
        $data['exp'] = strtotime('+30 days');
        $key = C('JAVA_KEY');
        $result = $jwt::encode($data, $key);
        return $result;
    }

    public static function generateToken($information = []) {
        $ext = [
            'expire_time' => C('QIPAO_JWT_EXPIRE') + time(),
            'random'      => mt_rand()
        ];
        //merge 消息数组
        $array = array_merge($information, $ext);
        $token = base64_encode(hash_hmac('SHA256', http_build_query($array), C("QIPAO_JWT_SECRET"), true)) . "." . base64_encode(http_build_query($array));
        return $token;
    }

    public static function getUid($token) {
        //截取基础信息数组
        $info_str = substr(strstr($token, '.'), 1);
        $param_str = base64_decode($info_str);
        //获取token中的秘钥字符串
        $secret = strstr($token, '.', true);
        //校验token是否合法
        if ($secret != base64_encode(hash_hmac('SHA256', $param_str, C("QIPAO_JWT_SECRET"), true))) return 0;
        //参数信息校验
        parse_str($param_str, $param_arr);

        $user_id = isset($param_arr['user_id']) ? $param_arr['user_id'] : 0;

        return $user_id;

    }

    public static function jwtDecode($string = '', $key = '', $func = ['HS256']) {
        require_once PLUGINS . '/JWT.php';
        $jwt = new \JWT();
        $key = $key ?: C('JAVA_KEY');
        $result = $jwt::decode($string, $key, $func);
        return $result;
    }

    public static function jwtToken() {
        require_once PLUGINS . '/JWT.php';
        $jwt = new \JWT();
        $data['iat'] = time();
        $data['exp'] = strtotime('+30 days');
        $key = C('JAVA_KEY');
        return $jwt::encode($data, $key);
    }

    public static function createToken($data = []) {
        require_once PLUGINS . '/JWT.php';
        $jwt = new \JWT();
        $key = C('JAVA_KEY');
        return $jwt::encode($data, $key);
    }

    public static function decodeToken($string = '', $key = '', $func = ['HS256']) {
        require_once PLUGINS . '/JWT.php';
        $jwt = new \JWT();
        $key = $key ?: C('JAVA_KEY');
        $result = $jwt::decode($string, $key, $func);
        return $result;
    }

    public static function javaBaseUrl() {
        $base_url = C('java_host');
        $base_url = trim($base_url, '/');
        $base_url = $base_url . '/api';
        return $base_url;
    }

    public function getToken() {
        $token = I('token', '');
        if (!$token) {
            $token = I('server.HTTP_TOKEN', '');
        }
        return $token;
    }

    //数字格式话
    public static function numberFormat($number) {
        $num = bcdiv($number, 10000, 2);
        if ($num > 1) {
            $number = $num . 'w';
        }
        return $number;
    }

    /**
     * @param $time 单位：s
     */
    public static function time_format($time) {
        $str = '';
        if ($time >= 86400) {
            $day = floor(bcdiv($time, 86400));
            $time = bcmod($time, 86400);
            $str .= $day . '天';
        }
        if ($time >= 3600) {
            $hour = floor(bcdiv($time, 3600));
            $time = bcmod($time, 3600);
            $str .= $hour . '小时';
        } else {
            $hour = 0;
        }
        if ($time >= 60) {
            $minute = floor(bcdiv($time, 60));
            $second = bcmod($time, 60);
            $str .= $minute . '分' . $second . '秒';
        } else {
            $second = $time;
            $str .= $second . "秒";
        }
        return $str;

    }

    /**
     * 判断六一活动是否开始
     */
    public static function checkActivityTime() {
        $begin_time = strtotime('2020-06-24 22:00:00');
        $end_time = strtotime('2020-06-27 23:59:59');
        $time = NOW_TIME;
        if ($time < $begin_time || $time > $end_time) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * @param $img_url
     * @return array state:1通过，2疑似，3不通过
     * @throws \ClientException
     * @throws \ServerException
     */
    public function aliGreen($img_url) {
        // 请替换成您的AccessKey信息。
        $iClientProfile = \DefaultProfile::getProfile("cn-shanghai", "LTAI4FfrEn9rWo8AAHxhXEfE", "flc5xLsRWBOXI2F2qgU4Em7IDoi57t");
        \DefaultProfile::addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        $client = new \DefaultAcsClient($iClientProfile);

        $request = new Green\ImageSyncScanRequest();
        $request->setMethod("POST");
        $request->setAcceptFormat("JSON");

        $task1 = [
            'dataId' => uniqid(),
            'url'    => $img_url
        ];
// 设置待检测的图片，一张图片对应一个检测任务。
// 多张图片同时检测时，处理时间由最后一张处理完的图片决定。
// 通常情况下批量检测的平均响应时间比单张检测要长。一次批量提交的图片数越多，响应时间被拉长的概率越高。
// 代码中以单张图片检测作为示例，如果需要批量检测多张图片，请自行构建多个检测任务。
// 一次请求中可以同时检测多张图片，每张图片可以同时检测多个风险场景，计费按照单图片单场景检测叠加计算。
// 例如：检测2张图片，场景传递porn和terrorism，则计费按照2张图片鉴黄和2张图片暴恐检测计算。
        $request->setContent(json_encode(["tasks" => [$task1], "scenes" => ["porn"]]));
        $response = $client->getAcsResponse($request);
        if (200 == $response->code) {
            $taskResults = $response->data;
            foreach ($taskResults as $taskResult) {
                if (200 == $taskResult->code) {
                    $sceneResults = $taskResult->results;
                    foreach ($sceneResults as $sceneResult) {
                        $scene = $sceneResult->scene;
                        $suggestion = $sceneResult->suggestion;
                        if ($suggestion == 'pass') {
                            $state = 1;
                        } elseif ($suggestion == 'review') {
                            $state = 2;
                        } else {
                            $state = 3;
                        }
                        return ['state' => $state, 'msg' => '成功'];
                    }
                } else {
                    return ['state' => 0, 'msg' => '鉴黄失败, code:' . $response->code];
                }
            }
        } else {
            return ['state' => 0, 'msg' => '鉴黄失败, code:' . $response->code];
        }
    }

    public static function exportExcel($header = [], $data = [], $sheetTitle = '', $filename = '') {
        Vendor('Phpexcel.PHPExcel');
        $objExcel = new \PHPExcel();
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
        $objExcel->setActiveSheetIndex(0);
        $objActSheet = $objExcel->getActiveSheet(0);
        if ($sheetTitle) {
            $objActSheet->setTitle($sheetTitle);
        }

        foreach ($header as $key => $value) {
            $col = \PHPExcel_Cell::stringFromColumnIndex($key);
            $objActSheet->setCellValue($col . '1', $value);
        }
        $i = 2;
        foreach ($data as $val) {
            $col_value = array_values($val);
            foreach ($col_value as $k => $v) {
                $col = \PHPExcel_Cell::stringFromColumnIndex($k);
                $objActSheet->setCellValue($col . $i, $v);
            }
            $i++;
        }

        ob_end_clean();
        $filename = $filename ?: date('YmdHis');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
        exit;
    }

    public function sensitive($word) {
        return false;
        $base_url = C('java_host');
        $base_url = trim($base_url, '/') . '/api';
        $url = $base_url . '/sensitive/sensitive/nameFilter?name=' . urlencode($word);
        $java_result = Helper::httpRequest($url, [], 1, ['x-token:' . TOKEN]);
        $result = json_decode($java_result, true);

        return isset($result['data']) && $result['data'] == true;
    }

    /**
     * @param $content
     * @param int $user_id
     * @param int $type 1昵称2房间名称3公屏4私聊5个性签名
     * @return bool
     */
    public static function checkTxt($content, $user_id = 0, $type = 1) {
        $redis = new RedisModel();

        $content = Helper::filterTxt($content);

        if (!$content || mb_strlen($content) <= 1) {
            return false;
        }

        $cache_result = $redis->checkSensitive($content);
        if ($cache_result != -1) {
            return $cache_result == 2;
        }

        $nc = new NetEase();
        if ($type == 1) {
            $result = $nc->checkTxt($content, 2);
        } else {
            $result = $nc->checkTxt($content);
        }

        D('SensitiveContent')->add([
            'user_id'         => $user_id,
            'content'         => $content,
            'add_time'        => NOW_TIME,
            'type'            => $type,
            'callback_result' => $result['callback_result'],
            'check_result'    => $result['action']
        ]);
        if ($result['action'] == 2) {
            $redis->addSensitive($content);
        } else {
            $redis->addSensitiveNot($content);
        }

        return $result['action'] == 2;
    }

    public static function is_weixin_visit() {
        return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false;
    }

    //判断是否模拟器
    public static function is_emulator($emulator) {
        return $emulator == 1;
    }

    /**
     * 验证语音是否涉嫌违规
     * @param $url
     * @return bool
     */
    public static function checkAudio($url) {
        $nc = new NetEase();
        $result = $nc->checkAudio($url);
        return $result['action'] == 2;
    }

    /**
     * 过滤文本，只保留中文、数字、英文、空格
     * @param $str
     * @return mixed
     */
    public static function filterTxt($str) {
        $face = ['[):]', '[:D]', '[;)]', '[:-o]', '[:p]', '[(H)]', '[:@]', '[:s]', '[:$]', '[:(]', "[:'(]", '[(a)]', '[8o|]', '[8-|]', '[+o(]', '[<o)]', '[|-)]', '[*-)]', '[:-#]', '[:-*]', '[^o)]', '[8-)]', '[(|)]', '[(u)]', '[(S)]', '[(*)]', '[(#)]', '[(R)]', '[({)]', '[(})]', '[(k)]', '[(F)]', '[(W)]', '[(D)]'];

        $str = str_replace($face, '', $str);
        preg_match_all('/[\x{4e00}-\x{9fa5}\d\w\s]+/u', $str, $result);
        $result = join('', $result[0]);
        $result = trim($result);
        return $result;
    }

    public static function sendEmchatMessage($target, $message, $ext, $from = '系统', $chat_type = 'chatrooms') {
        $emchat = new Emchat();
        $emchat->sendTxt($from, $chat_type, $target, $message, $ext);
    }

    public static function checkGoodNumber($number) {
        $redis = \Think\Cache::getInstance();
        $is_good_number = $redis->hexists('goodNumber', $number);
        return $is_good_number ? 1 : 0;
    }

    public static function sendUserNews($user_id, $title, $content) {
        D("Api/UserNews")->addData($user_id, $content, $title);
        S('user:news:count:' . $user_id, null);
        S('user:news:info:' . $user_id, null);
    }

    public static function notDisplayRoom($room_code, $rank_id = 0) {
        $hide_rooms = C('HIDE_ROOM_BY_LEVEL');
        if ($hide_rooms) {
            if (isset($hide_rooms[$room_code]) && $hide_rooms[$room_code] > 0 && $rank_id < $hide_rooms[$room_code]) {
                return true;
            }
        }

        return false;
    }

    public static function notDisplayRoomList() {
        $not_display_room = C('NOT_DISPLAY_ROOM');
        $list = [5525586, 4382184, 20203, 5672571, 20206, 20202, 20212];
        if (empty($not_display_room)) {
            $list = array_merge($not_display_room, $list);
        }
        return $list;
    }


    public static function exportCsv($header = [], $data = [], $filename = '') {
        ini_set('memory_limit', '1024M'); //设置程序运行的内存
        ini_set('max_execution_time', 0); //设置程序的执行时间,0为无上限
        ob_end_clean();                   //清除内存
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename . '.csv');
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
        fputcsv($fp, $header);
        $index = 0;
        foreach ($data as $item) {
            if ($index == 5000) { //每次写入1000条数据清除内存
                $index = 0;
                ob_flush();//清除内存
                flush();
            }
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
        exit();
    }

    //送给被邀请的用户礼包
    public static function sendUserGiftBag($user_id, $parent_id) {
        $result = [
            'gift_bag_id' => 0,
            'url'         => ''
        ];
        $parent = M('User')->where(['user_id' => $parent_id])->find();
        if ($parent['gift_bag_id'] > 0 && $parent['gift_bag_quantity'] > 0) {
            $gift_bag_info = M('GiftBag')->find($parent['gift_bag_id']);
            if ($gift_bag_info) {
                if (M('User')->where(['user_id' => $parent_id])->setDec('gift_bag_quantity', 1)) {
                    $result['gift_bag_id'] = $parent['gift_bag_id'];
                    M('GiftBagReceive')->add([
                        'user_id'     => $user_id,
                        'parent_id'   => $parent_id,
                        'gift_bag_id' => $parent['gift_bag_id'],
                        'add_time'    => NOW_TIME,
                    ]);
                    $result['url'] = 'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/images/new.png?v=1';
                    $gift_bag_detail = M('GiftBagDetail')->where(['gift_bag_id' => $parent['gift_bag_id']])->select();
                    $gd = [];
                    foreach ($gift_bag_detail as $detail) {
                        switch ($detail['type']) {
                            case 1://赠送金币
                                $gd [] = '金币 X ' . $detail['gold'];

                                D('Api/User')->serUserMoney($user_id, $detail['gold'], 1);
                                D('Api/AccountLog')->addData($user_id, $detail['gold'], $gift_bag_info['name'], 34);

                                break;
                            case 2://赠送礼物到背包
                                $gd [] = $detail['name'] . ' X ' . $detail['quantity'] . '个';
                                D('Api/GiftBackpack')->sendBackpackGift($user_id, $detail['foreign_id'], $detail['quantity']);
                                break;
                            case 3://赠送坐骑
                            case 4://赠送头像框
                                $gd [] = $detail['name'] . ' X ' . $detail['days'] . '天';
                                D('MallOrders')->give($detail['foreign_id'], $user_id, $detail['days']);
                                break;
                        }
                    }
                    $title = '新用户专享大礼包';
                    $content = '尊敬的用户：恭喜您获得平台新手大礼包。礼包内容：' . implode('、', $gd);
                    Helper::sendUserNews($user_id, $title, $content);
                }
            }
        }
        return $result;
    }
    //送给被邀请的用户礼包
    public static function sendChannelUserGiftBag($user_id, $gift_bag_id) {
        $gift_bag_info = M('GiftBag')->find($gift_bag_id);
        if ($gift_bag_info) {
            M('GiftBagReceive')->add([
                'user_id'     => $user_id,
                'parent_id'   => 0,
                'gift_bag_id' => $gift_bag_id,
                'add_time'    => NOW_TIME,
            ]);
            $gift_bag_detail = M('GiftBagDetail')->where(['gift_bag_id' => $gift_bag_id])->select();
            $gd = [];
            foreach ($gift_bag_detail as $detail) {
                switch ($detail['type']) {
                    case 1://赠送金币
                        $gd [] = '金币 X ' . $detail['gold'];

                        D('Api/User')->serUserMoney($user_id, $detail['gold'], 1);
                        D('Api/AccountLog')->addData($user_id, $detail['gold'], $gift_bag_info['name'], 34);

                        break;
                    case 2://赠送礼物到背包
                        $gd [] = $detail['name'] . ' X ' . $detail['quantity'] . '个';
                        D('Api/GiftBackpack')->sendBackpackGift($user_id, $detail['foreign_id'], $detail['quantity']);
                        break;
                    case 3://赠送坐骑
                    case 4://赠送头像框
                        $gd [] = $detail['name'] . ' X ' . $detail['days'] . '天';
                        D('MallOrders')->give($detail['foreign_id'], $user_id, $detail['days']);
                        break;
                }
            }
            $title = '新用户专享大礼包';
            $content = '尊敬的用户：恭喜您获得平台新手大礼包。礼包内容：' . implode('、', $gd);
            static::sendUserNews($user_id, $title, $content);
        }
    }

    /**
     * 请求新lumen框架获取数据
     * @param $api_name
     * @param $data
     * @param string $type
     * @return mixed
     */
    public static function lumenApi($api_name, $data, $type = 'post') {
        if (env('APP_ENV') == 'local') {
            $url = env('LOCAL_NAPI_HOST');
        } else {
            $url = env('PRODUCTION_NAPI_HOST');
        }
        $url = $url . '/' . trim($api_name, '/');
        if ($type == 'post') {
            $result = static::CurlPost($url, $data);
        } else {
            $result = static::curl_gets($url, $data);
        }
        return $result;
    }

    //判断用户是否是地域黑名单里面的
    public  function  userRegionBlacklist($user_id='uid'){
        $ip_limit_stitch =M('Config')->where(['key'=>'IP_LIMIT_SWITCH'])->getField('value');
        if ($ip_limit_stitch ==2){
            return 0;
        }
        $ip = get_client_ip(0, true);
//        $ip = '115.239.212.133';
      //  $ip = '60.190.223.77';
        $res =Helper::lumenApi('service/aliyun/ip',['ip'=>$ip],'get');
        if ($res['code']==200){
               $province =$res['data']['Province'];
               $city =$res['data']['City'];
               $regions = D('Redis')->region_blacklist();
               if (in_array($province,$regions) || in_array($city,$regions)){
                       $user_white_list = D('Redis')->user_whitelist();
                       if (in_array($user_id,$user_white_list)){
                           return 0;
                       }
                   return 1;
               }else{
                   return 0;
               }
        }
        return 0;
    }

    //限制登录地域黑名单里面的
    public static function userLoginRegionBlacklist($user_id='uid'){
        $redis = new RedisModel();
//        $ip_limit_stitch =M('Config')->where(['key'=>'IP_LOGIN_LIMIT_SWITCH'])->getField('value');
        $ip_limit_stitch = C('IP_LOGIN_LIMIT_SWITCH');
        if ($ip_limit_stitch ==2){
            return 0;
        }
        $ip = get_client_ip(0, true);
       // $ip = '115.239.212.133';
         // $ip = '1.195.127.207';
          //$ip = '1.192.119.149';
        $res =Helper::lumenApi('service/aliyun/ip',['ip'=>$ip],'get');
        if ($res['code']==200){
            $province =$res['data']['Province'];
            $city =$res['data']['City'];
            $regions = $redis->login_region_blacklist();
            if (in_array($province,$regions) || in_array($city,$regions)){
                $user_white_list =$redis->user_whitelist();
                if (in_array($user_id,$user_white_list)){
                    return 0;
                }
                return 1;
            }else{
                return 0;
            }
        }
        return 0;
    }



    //获取符合体条件的游戏列表
    public  function  gameList(){
        if (defined('UID')){
            $rank_id = M('User')->where('user_id='.UID)->getField('rank_id');
        }else{
            $rank_id =0;
        }
        $where['start_time'] =['lt',time()];
        $where['end_time'] =['gt',time()];
        $where['user_grade'] =['elt',$rank_id];
        $where['status'] =1;
        $data = M('GameEntrance')->where($where)->select();
        $new_data =[];
        if ($data){
            $hour = date('H',time());
            $game_ids = array_column($data,'time_slot','game_id');
            foreach ($game_ids as  $key=>$game_id){
                $arr_time_slot =json_decode($game_id,true);
                foreach ($arr_time_slot as $k=>$value){
                    if ($value[0] <= $hour &&  $value[1] >= $hour){
                        $new_data[] =$key;
                    }
                }
            }
        }
        return $new_data;
    }


    //获取游戏是否开启
    public static function verifyBoxActivity($game_type_id){
        if (defined('UID')){
            $rank_id = M('User')->where('user_id='.UID)->getField('rank_id');
        }else{
            $rank_id =0;
        }
        $where['start_time'] =['lt',time()];
        $where['end_time'] =['gt',time()];
        $where['user_grade'] =['elt',$rank_id];
        $where['status'] =1;
        $where['game_id'] =$game_type_id;
        $data = M('GameEntrance')->where($where)->find();
        if (!$data){
            return 1;
        }else{
            $status =1;
            $hour = date('H',time());
            $game_ids = [$data['game_id']=>$data['time_slot']];
            foreach ($game_ids as  $key=>$game_id){
                $arr_time_slot =json_decode($game_id,true);
                foreach ($arr_time_slot as $k=>$value){
                    if ($value[0] <= $hour &&  $value[1] >= $hour){
                        $status =0;
                        break;
                    }
                }
            }
            return $status;
        }
    }

    //获取国庆活动头像框id
    public function  headPictureIds(){
        //最后一个为坐骑id
        $ids = [57,58,59,60];
        return $ids;
    }

    //获取国庆活动兑换头像框
    public function  exchangeHeaderPic(){
        $ids = [54,55,56];
        return $ids;
    }

    //国庆活动钥匙扣名称
    public  function   keyBuckleName(){
        $names =['钥匙扣1号','钥匙扣2号','钥匙扣3号','钥匙扣4号','钥匙扣5号','钥匙扣6号'];
        return $names;
    }
    //国庆活动兑换钥匙扣需要的积分
    public  function  buckleScore(){
        $score =['90000','100000','110000','120000','130000','140000'];
        return $score;
    }

    //国庆活动抱枕被名称
    public  function   pillowName(){
        $names =['抱枕被1号','抱枕被2号','抱枕被3号','抱枕被4号','抱枕被5号'];
        return $names;
    }

    //国庆活动抱枕被兑换需要积分
    public  function   exchangePillowScore(){
        $score =['180000','190000','200000','210000','220000'];
        return $score;
    }

    //判断是否是进入房间隐身用户
    public static function roomInvisible($user_id) {
        $invisible_users = C('JOIN_ROOM_INVISIBLE_USER');
        $user_code = D('Api/UserData')->getUserCode($user_id);

        $user_nobility_level = (new RedisModel())->getUserNobilityValue($user_id, 'level');

        if (is_array($invisible_users) && in_array($user_code, $invisible_users) || $user_nobility_level >= 16) {//后台设置进房进房隐身或爵位在皇爵及以上
            $configInfo = D('Api/UserConfig')->getUserInform($user_id);
            if (isset($configInfo['is_invisible']) && $configInfo['is_invisible'] == 1) {
                return 1;
            } else {
                return 2;
            }
        } else {
            return 0;
        }
    }
    //判断是否房间榜单隐身
    public static function roomRankInvisible($user_id) {
        $user_nobility_level = (new RedisModel())->getUserNobilityValue($user_id, 'level');

        if ($user_nobility_level >= 10) {//爵位在公爵及以上
            $configInfo = D('Api/UserConfig')->getUserInform($user_id);
            if (isset($configInfo['rank_invisible']) && $configInfo['rank_invisible'] == 1) {
                return 1;
            } else {
                return 2;
            }
        } else {
            return 0;
        }
    }

    public static function getHeaders() {
        $headers = [];
        if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
            $headers = $result;
        } else {
            foreach ($_SERVER as $key => $val) {
                if (0 === strpos($key, 'HTTP_')) {
                    $key = str_replace('_', '-', strtolower(substr($key, 5)));
                    $headers[$key] = $val;
                }
            }
        }
        $headers = array_change_key_case($headers);
        return $headers;
    }

    public static function functionLimit() {
        $clienttype = I('server.HTTP_CLIENTTYPE');
        $channelid = I('server.HTTP_CHANNELID');
        $app_version = I('server.HTTP_APPVERSION');
        $app_version = str_replace('.', '', $app_version);
        if ($clienttype == 'android' && $channelid == 'kuaishou') {
            return true;
        }
        $config = C('IOS_VERSION');
        $config = json_decode($config, true);
        $config_version = $config['otherVersion'] ?? '';
        if ($config_version) {
            $config_version = str_replace('.', '', $config_version);
        }
        if ($clienttype == 'appstore' && $app_version > $config_version) {
            return true;
        }
        return false;
    }

    //出生日期转年龄
    public static function birthToAge($birth, $type = false) {
        if($birth == '0000-00-00') return 0;
        if ($type) $birth = strtotime($birth);

        //格式化出生时间年月日
        $byear = date('Y', $birth);
        $bmonth = date('m', $birth);
        $bday = date('d', $birth);

        //格式化当前时间年月日
        $tyear = date('Y');
        $tmonth = date('m');
        $tday = date('d');

        //开始计算年龄
        $age = $tyear - $byear;
        if ($bmonth > $tmonth || $bmonth == $tmonth && $bday > $tday) {
            $age--;
        }
        return $age;
    }

    //获取随机昵称
    public static function getRandomNickname() {
        return static::getRandomChinese(1) . static::getRandomChinese(2);
    }

    //获取随机中文
    //$type = 1获取随机姓 $type = 2 获取随机名
    private static function getRandomChinese($type)
    {
        if ($type == 1) {
            $redis_key = 'random:lastname';
            $filename = 'random_last_name.txt';
        } else {
            $redis_key = 'random:firstname';
            $filename = 'random_first_name.txt';
        }

        if (!app('redis')->exists($redis_key)) {
            $file = fopen(base_path() . "/{$filename}", "r");
            $result = [];
            while (!feof($file)) {
                $result[] = str_replace(["\s", "\r", "\n"], '', fgets($file));
            }
            fclose($file);
            app('redis')->sadd($redis_key, ...$result);
            return $result[mt_rand(0, count($result) - 1)];
        } else {
            return app('redis')->srandmember($redis_key);
        }
    }

    public function getRandomLastName()
    {
        $redis_key = 'random:lastname';
        if (!$this->redis->exists($redis_key)) {
            $file = fopen(APP_PATH . "../random_last_name.txt", "r");
            $result = [];
            while (!feof($file)) {
                $result[] = str_replace(["\s", "\r", "\n"], '', fgets($file));
            }
            fclose($file);
            $this->redis->sadd($redis_key, ...$result);
            return $result[mt_rand(0, count($result) - 1)];
        } else {
            return $this->redis->srandmember($redis_key);
        }
    }

    public static function getRandomHeadPicture() {
        $arr = [
//            'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/1.jpg',
//            'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/2.jpg',
//            'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/3.jpg',
//            'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/4.jpg',
//            'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/5.jpg',
//            'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/6.jpg',
//            'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/7.jpg',
//            'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/8.jpg',
//            'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/9.jpg',
//            'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/10.jpg',
//            'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/11.jpg',
//            'https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/12.jpg',
              'http://ice2.hyutrain.com/statics/default-avatar.png'
        ];
        return $arr[mt_rand(0, count($arr) - 1)];
    }

    public static function isPlanet() {
        $vestName = $_SERVER['HTTP_VESTNAME'] ?? '';
        return $vestName == 'qipaoxingqiu';
    }
    //如果是气泡星球,隐藏部分内容
    public static function hidePlanet() {
        $switch = C('HIDE_PLANET_CONTENT');
        $switch = in_array($switch, [1, 2]) ? $switch : 1;
        if (self::isPlanet()) {
            return $switch == 1;
        }
    }

    public static function get_real_ip($type = 0,$adv=false) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
        // IP 地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

    public static function indexToAssoc($array, $key){
        return array_combine(array_column($array, $key), array_values($array));
    }

    public static function getArrayColumn($array, $key){
        return array_filter(array_column($array, $key));
    }

}
